package com.keyware.kd.controller.user;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.keyware.kd.exception.RemoteCallFailedException;
import com.keyware.kd.repository.entity.UserSecret;
import com.keyware.kd.service.itf.auditlog.UserAuditLogService;
import com.keyware.kd.service.itf.user.UserServiceRemove;
import com.keyware.kd.service.itf.usersecret.UserSecretService;
import com.keyware.kd.vo.user.UserVo;
import com.keyware.utils.*;
import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.keyware.kd.controller.BaseController;
import com.keyware.kd.listener.SessionCounter;
import com.keyware.kd.repository.entity.department.Department;
import com.keyware.kd.repository.entity.number.NumberBuilder;
import com.keyware.kd.repository.entity.safemanagement.SafeManagement;
import com.keyware.kd.repository.entity.user.User;
import com.keyware.kd.service.itf.auditlog.AuditLogService;
import com.keyware.kd.service.itf.department.DepartmentService;
import com.keyware.kd.service.itf.jurisdiction.MenuService;
import com.keyware.kd.service.itf.message.MessageService;
import com.keyware.kd.service.itf.number.NumberBuilderService;
import com.keyware.kd.service.itf.safemanagement.SafeManagementService;
import com.keyware.kd.service.itf.user.UserService;
import com.keyware.kd.task.util.AjaxMessage;
import com.keyware.kd.utils.Constant;
import com.keyware.kd.vo.SafeManagementVo;

@Controller
@RequestMapping("/userController")
public class UserController extends BaseController{
	public static Logger logger = Logger.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	
	@Resource
	private AuditLogService auditLogService;
	
	@Autowired
	private SafeManagementService safeManagementService;

	
	@Autowired
	private NumberBuilderService numberBuilderService;
	
	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private UserAuditLogService userAuditLogService;
	
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private SessionDAO sessionDAO;

	@Autowired
	private UserSecretService userSecretService;

	@Autowired
	UserServiceRemove userServiceRemove;
	
	@RequestMapping(value="/showIndexPageBody",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public String showIndexPageBody(){
		return "portal/home_body";
	}
	
	@RequestMapping(value="/showUserList",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public String showUserList(){
		
		return "portal/showUserList";
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转用户列表页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value={"/user"})
	public String userPage(){
		String  customer = numberBuilderService.getCustomerId();
		//查询所有的部门
		List<Department> departmentList = departmentService.selectAll();
		//根据当前登录人的id查询用户列表下的职务
		List<User> usersList = userService.selectAll(getUser_idFormSession("userId"));
		List<String> list=new ArrayList<String>();
		for(User user:usersList){
			if(user.getPost()!=null && !list.contains(user.getPost())){
				list.add(user.getPost());
			}
		}
		request.setAttribute("departmentList", departmentList);
		request.setAttribute("postList", list);
		request.setAttribute("numCode", customer);
		return "user/userList";
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转用户列表页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value={"/logoutUser"})
	public String logoutUserPage(){
		return "user/logoutUserList";
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转用户列表页面
	 * @return
	 *@date 2016-06-30
	 */
	@RequestMapping(value={"/userPwdResetPage"})
	public String userPwdResetListPage(){
		return "user/userPwdResetList";
	}
	
	/**
	 *@author 申鹏飞
	 *@title 跳转用户管理添加页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/addPage" })
	public String addPage(){
		List<SafeManagement> list = safeManagementService.selectInfo();
		String  customer = getUser_idFormSession("customCode");
		request.setAttribute("numCode", customer);
		NumberBuilder numberBuilder = numberBuilderService.selectByPrimaryKey("platformPwdLevel");
		if(numberBuilder!=null && numberBuilder.getNumber().equals("user")){//用户密级
			list = safeManagementService.selectAll();
			List<SafeManagementVo> safelist = new ArrayList<SafeManagementVo>();
			for(SafeManagement safeManagement : list){
				SafeManagementVo safeManagementVo = new SafeManagementVo();
				safeManagementVo.setId(safeManagement.getId());
				safeManagementVo.setMaximumPwdLength(safeManagement.getMaximumPwdLength());
				safeManagementVo.setMinimumPwdLength(safeManagement.getMinimumPwdLength());
				safeManagementVo.setProjectSource(safeManagement.getProjectSource());
				safeManagementVo.setPwdChangeCycle(safeManagement.getPwdChangeCycle());
				safeManagementVo.setPwdExpirationTime(safeManagement.getPwdExpirationTime());
				safeManagementVo.setPwdLocktimes(safeManagement.getPwdLocktimes());
				safeManagementVo.setSystemLevel(safeManagement.getSystemLevel());
				safeManagementVo.setUserInactiveTime(safeManagement.getUserInactiveTime());
				long systemLevel = safeManagement.getSystemLevel();
				if(systemLevel == 0){
					safeManagementVo.setSystemLevelName("普通");
				}else if(systemLevel == 1){
					safeManagementVo.setSystemLevelName("秘密");
				}else if(systemLevel == 2){
					safeManagementVo.setSystemLevelName("机密");
				}else if(systemLevel == 3){
					safeManagementVo.setSystemLevelName("绝密");
				}
				safelist.add(safeManagementVo);
			}
			request.setAttribute("safeList", safelist);
			request.setAttribute("safeListJson", JsonUtils.toJson(list));
			request.setAttribute("userNumber", numberBuilderService.getUserNumber());
		}else{
			SafeManagement safeManagement = list.get(0);
			request.setAttribute("userNumber", numberBuilderService.getUserNumber());
			Long pwdMinLength=(long) 0;
			Long pwdMaxLength=(long) 0;
			if(safeManagement!=null){
				pwdMinLength=safeManagement.getMinimumPwdLength();
				pwdMaxLength=safeManagement.getMaximumPwdLength();
				request.setAttribute("pwdMinLength",pwdMinLength );
				request.setAttribute("pwdMaxLength", pwdMaxLength);
			}
		}
		//当前系统密级设置
		request.setAttribute("sysPwdLevel", null!=numberBuilder?numberBuilder.getNumber():"");
		return "user/userAddPage";	
	}
	/**
	 *@author 申鹏飞
	 *@title 添加用户管理信息
	 *@param user
	 * @return
	 *@date 2016-06-29
	 */
	@RequestMapping(value="/add",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxMessage add(@ModelAttribute User user){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			userServiceRemove.add(ajaxMessage,user,request);
		}catch (RemoteCallFailedException e) {
			ajaxMessage.setCode("0");
			ajaxMessage.setMessage(e.getMessage());
		}
		catch (Exception e) {
			logger.error(e);
			ajaxMessage.setCode("0");
			ajaxMessage.setMessage(Constant.ERROE_MESSAGE);
		}
		return ajaxMessage;
		
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转用户管理修改页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/editPage" })
	public String editPage(){
		String id=request.getParameter("id");
		request.setAttribute("id", id);
		User selectByPrimaryKey = userService.selectByPrimaryKey(id);
		String numCode = getUser_idFormSession("customCode");
		NumberBuilder numberBuilder = numberBuilderService.selectByPrimaryKey("platformPwdLevel");
		if(numCode != null && (numCode.equals(ProjectIdentNew.siyuan17suo) || numCode.equals(ProjectIdentNew.guiyangshiyuan))){
			//获取人员密级
			UserSecret userSecret = userSecretService.selectByPrimaryKey(id);
			request.setAttribute("userSecret", userSecret);
		}

		if(numberBuilder!=null && numberBuilder.getNumber().equals("user")){//用户密级
			List<SafeManagement> list=safeManagementService.selectAll();
			List<SafeManagementVo> safelist = new ArrayList<SafeManagementVo>();		
			SafeManagement safeManagement2 = new SafeManagement();
			String uesrRankId = selectByPrimaryKey.getUesrRankId() == null ? "" : selectByPrimaryKey.getUesrRankId();
			if(StringUtils.hasText(uesrRankId)){
				safeManagement2.setMinimumPwdLength(new Long(1000));
				safeManagement2.setMaximumPwdLength(new Long(1000));
			}
			for(SafeManagement safeManagement : list){
				if(uesrRankId.equals(safeManagement.getId())){
					safeManagement2 = safeManagement;
				}
				
				SafeManagementVo safeManagementVo = new SafeManagementVo();
				safeManagementVo.setId(safeManagement.getId());
				safeManagementVo.setMaximumPwdLength(safeManagement.getMaximumPwdLength());
				safeManagementVo.setMinimumPwdLength(safeManagement.getMinimumPwdLength());
				safeManagementVo.setProjectSource(safeManagement.getProjectSource());
				safeManagementVo.setPwdChangeCycle(safeManagement.getPwdChangeCycle());
				safeManagementVo.setPwdExpirationTime(safeManagement.getPwdExpirationTime());
				safeManagementVo.setPwdLocktimes(safeManagement.getPwdLocktimes());
				safeManagementVo.setSystemLevel(safeManagement.getSystemLevel());
				safeManagementVo.setUserInactiveTime(safeManagement.getUserInactiveTime());
				long systemLevel = safeManagement.getSystemLevel();
				if(systemLevel == 0){
					safeManagementVo.setSystemLevelName("普通");
				}else if(systemLevel == 1){
					safeManagementVo.setSystemLevelName("秘密");
				}else if(systemLevel == 2){
					safeManagementVo.setSystemLevelName("机密");
				}else if(systemLevel == 3){
					safeManagementVo.setSystemLevelName("绝密");
				}
				safelist.add(safeManagementVo);
			}
			request.setAttribute("safeManagement", safeManagement2);
			request.setAttribute("safeList", safelist);
			request.setAttribute("safeListJson", JsonUtils.toJson(list));
		}	
	
		request.setAttribute("numCode", numCode);
		if(selectByPrimaryKey != null)
			request.setAttribute("userInfo", selectByPrimaryKey);
		//当前系统密级设置
		
		request.setAttribute("sysPwdLevel", null!=numberBuilder?numberBuilder.getNumber():"");
		return "user/userEditPage";	
	}
	/**
	 *@author 申鹏飞
	 *@title 获取用户管理信息
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/viewInfo" })
	@ResponseBody
	public String viewInfo(){
		String id=request.getParameter("id");
		User user=userService.selectByPrimaryKey(id);
		return JsonUtils.objectToJsonString(user);	
	}
	/**
	 *@author 申鹏飞
	 *@title 修改用户管理信息
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/edit",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxMessage edit(@ModelAttribute User user){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			List<User> selectByUserNumber = userService.selectByUserNumber(user.getUserNumber());
			if(selectByUserNumber.size() > 0){
				if(selectByUserNumber.size() == 1 ){
					User user2 = selectByUserNumber.get(0);
					if(!user2.getId().equals(user.getId())){
						ajaxMessage.setCode("0");
						ajaxMessage.setMessage("员工编号已存在");     // 修改提示信息与内容保持一致，‘用户编号已存在’--‘员工编号已存在’
						return ajaxMessage;
					}
				}else{
					ajaxMessage.setCode("0");
					ajaxMessage.setMessage("员工编号已存在");
					return ajaxMessage;
				}
			}
			userService.updateByPrimaryKey(user);
			//修改用户的日志
			HttpSession session = request.getSession();
			String userName = (String) session.getAttribute("userName");
			String comments = userName + "修改了用户" + user.getUserName() + "的信息";
			auditLogService.insertLog("修改人员", "用户列表", comments, request);
			String  numCode = getUser_idFormSession("customCode");
			if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
				User safeUser = userService.selectUserByUserId("safesecret");
				messageService.insertMessage("修改用户"+user.getUserName()+"", "用户管理", null,safeUser.getId(), "", "0","K");
			}
			if(numCode != null && (numCode.equals(ProjectIdentNew.siyuan17suo) || numCode.equals(ProjectIdentNew.guiyangshiyuan))){
				//查询人员密级信息
				UserSecret userSecret = userSecretService.selectByPrimaryKey(user.getId());
				if(userSecret == null){
					//新增人员密级
					UserSecret secret = new UserSecret();
					secret.setId(user.getId());
					secret.setSecret(user.getSecret());
					userSecretService.insertSelective(secret);
				}else {
					//修改人员密级
					userSecret.setSecret(user.getSecret());
					userSecretService.updateByPrimaryKey(userSecret);
				}
			}
			ajaxMessage.setCode("1");
			ajaxMessage.setMessage("保存成功");
		} catch (Exception e) {
			logger.error(e);
			ajaxMessage.setCode("0");
			ajaxMessage.setMessage(Constant.ERROE_MESSAGE);
		}
		return ajaxMessage;
	}
	/**
	 *@author 申鹏飞
	 *@title 查询用户管理页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/select",produces = "application/json; charset=utf-8")
	@ResponseBody
	public PaginationUtil selectAll(@ModelAttribute User user){
		PaginationUtil paginationUtil = new PaginationUtil();
		//paginationUtil.before(request);
		String user_idFormSession = getUser_idFormSession("userId");
		if("sysadmin".equals(user_idFormSession))
			user.setIsSys("sysadmin");
		
		if("请输入姓名...".equals(user.getUserNameForSerch())){
			user.setUserNameForSerch(null);
		}
		user.setUserStatus(1L);
		user.setProjectSource(Constant.projectName);
		String  numCode = getUser_idFormSession("customCode");
		List<User> userList = null;
		if(numCode != null && numCode.equals(ProjectIdentNew.siyuan17suo)){
			userList = userService.selectByUserInfo17suo(user);
		} else {
			userList = userService.selectByUserInfo(user);
		}
		PageUtils pageUtils = new PageUtils();
		pageUtils.getPageBefore(paginationUtil,userList,request);
		return paginationUtil;
	}
	/**
	 *@author 申鹏飞
	 *@title 查询注销用户页 面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/selectLogOutUser",produces = "application/json; charset=utf-8")
	@ResponseBody
	public PaginationUtil selectLogOutUser(String name){
		PaginationUtil paginationUtil=new PaginationUtil();
		paginationUtil.before(request);
		if("请输入姓名...".equals(name))     // 信息显示与内容一致 
			name = null;
		List<?> user=userService.selectLogOutUser(name);
		paginationUtil.after(user);
		return paginationUtil;
	}
	
	/**
	 *@ author 			申鹏飞
	 *@ title 			删除用户管理信息
	 *@ return
	 *@ date 2016-06-17
	 */
	@RequestMapping(value = "/delete",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delete(){
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		try {
			userServiceRemove.delete(userName,request);
			return "删除成功";
			
		} catch (Exception e) {


			logger.error(e);
			return Constant.ERROE_MESSAGE;
		}
	}
	
	/**
	 *@author 申鹏飞
	 *@title 删除重置密码页面信息
	 * @return
	 *@date 2016-06-30
	 */
	@RequestMapping(value = "/delPwdResetList",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delPwdResetList(){
		HttpSession session = request.getSession();
		String userName=(String) session.getAttribute("userName");
		try {
			List<String> listId=IdComposeListUtil.listId(request);
			String userNames = "";
			for(String id : listId){
				User u = userService.selectByPrimaryKey(id);
				if("".equals(userNames)){
					userNames = u.getUserName();
				}else{
					userNames += "," + u.getUserName();
				}
			}
			userService.delPwdResetList(listId);
			//删除重置密码的日志
			String comments = userName + "删除了用户" + userNames +"初始密码信息";
			auditLogService.insertLog("删除", "初始密码", comments, request);
			String  numCode = getUser_idFormSession("customCode");
			if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
				User safeUser = userService.selectUserByUserId("safesecret");
				messageService.insertMessage("删除用户"+userNames+"的重置密码", "用户管理", null,safeUser.getId(), "", "0","K");
			}
			return "删除成功";
		} catch (Exception e) {
			logger.error(e);
			return Constant.ERROE_MESSAGE;
		}
	}
	/**
	 *@author 申鹏飞
	 *@title 修改用户状态
	 *@return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/updateStatus",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxMessage updateStatus(@ModelAttribute User user){
		HttpSession session = request.getSession();
		String userName=(String) session.getAttribute("userName");
		AjaxMessage ajaxMessage = new AjaxMessage();
		String ids = user.getIds();
		String userNames = "";
		String logName = "";
		if(StringUtils.hasText(ids)){
			String[] split = ids.split(",");
			for(String id : split){
				user.setId(id);
				userService.updateStatus(user);
				//记录日志
				User u = userService.selectByPrimaryKey(id);
				if("".equals(userNames)){
					userNames = u.getUserName();
				}else{
					userNames += "," + u.getUserName();
				}
				logName="open";
				if(user.getUserStatus()==1){
					logName="close";
				}
			}
			String  numCode = getUser_idFormSession("customCode");
			if("open".equals(logName)){
				String comments = userName + "启用了用户" + userNames;
				auditLogService.insertLog("启用", "用户列表", comments, request);
				if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
					User safeUser = userService.selectUserByUserId("safesecret");
					messageService.insertMessage("启用用户"+userNames+"", "用户管理", null,safeUser.getId(), "", "0","K");
				}
				ajaxMessage.setMessage("启用成功");
			}else if("close".equals(logName)){
				String comments = userName + "禁用了用户" + userNames;
				auditLogService.insertLog("禁用", "用户列表", comments, request);
				if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
					User safeUser = userService.selectUserByUserId("safesecret");
					messageService.insertMessage("禁用用户"+userNames+"", "用户管理", null,safeUser.getId(), "", "0","K");
				}
				ajaxMessage.setMessage("禁用成功");
			}
		}
		
		return ajaxMessage;	
	}
	/**
	 *@author 申鹏飞
	 *@title 修改用户锁定状态
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/updateLock",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String updateLock(@ModelAttribute User user){
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		List<String> listId=IdComposeListUtil.listId(request);
		userService.unlock(listId);
		String userNames = "";
		for(int i=0;i<listId.size();i++){
			User u = userService.selectByPrimaryKey(listId.get(i));
			if("".equals(userNames)){
				userNames = u.getUserName();
			}else{
				userNames += "," + u.getUserName();
			}
		}
		String  numCode = getUser_idFormSession("customCode");
		String comments = userName + "将用户" + userNames + "解锁";
		auditLogService.insertLog("解锁", "用户列表", comments, request);
		if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
			User safeUser = userService.selectUserByUserId("safesecret");
			messageService.insertMessage("解锁用户"+userNames+"", "用户管理", null,safeUser.getId(), "", "0","K");
		}
		return "解锁成功";	
	}
	/**
	 *@author 申鹏飞
	 *@title 获取用户登陆名和用户名
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/getUserIdName",method = RequestMethod.GET)
	@ResponseBody
	public String getUserIdName(){
		List<User> userIdNameMap=userService.getUserIdName();
		return JsonUtils.arrayListToJsonString(userIdNameMap);
	}
	/**
	 *@author 申鹏飞
	 *@title 用户注销
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/updateLogout",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String updateLogout(@ModelAttribute User user){
		String  numCode = getUser_idFormSession("customCode");
		List<String> listId=IdComposeListUtil.listId(request);
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		if("1".equals(request.getParameter("logOut"))||request.getParameter("logOut")=="1"){
			userService.updateLogout(listId);
			User userupdate = new User();
			//注销用户的日志
			String userNames = "";
			for(int i=0;i<listId.size();i++){
				User u = userService.selectByPrimaryKey(listId.get(i));
				userupdate.setId(listId.get(i));
				userupdate.setLogoutTime(DateUtils.getDateTime());
				userService.updateByPrimaryKey(userupdate);
				if("".equals(userNames)){
					userNames = u.getUserName();
				}else{
					userNames += "," + u.getUserName();
				}
			}
			String comments = userName + "注销了用户" + userNames;
			auditLogService.insertLog("注销人员", "用户列表", comments, request);
			
			if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
				User safeUser = userService.selectUserByUserId("safesecret");
				messageService.insertMessage("注销用户"+userNames+"", "用户管理", null,safeUser.getId(), "", "0","K");
			}
			
		}
		if(!"1".equals(request.getParameter("logOut"))&&request.getParameter("logOut")!="1"){
			Integer userCount = Constant.userCount;
			if(0 != userCount){
				List<User> selectAll = userService.selectAll(null);
				if(userCount < (selectAll.size()+listId.size()))
					return "当前版本只允许新建"+Constant.userCount+"个用户";
			}
			userService.recovery(listId);
			//还原用户的日志
			String userNames = "";
			for(int i=0;i<listId.size();i++){
				User u = userService.selectByPrimaryKey(listId.get(i));
				String comments = userName + "还原了用户" + u.getUserName();
				auditLogService.insertLog("还原人员", "注销用户列表", comments, request);
				if("".equals(userNames)){
					userNames = u.getUserName();
				}else{
					userNames += "," + u.getUserName();
				}
				if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
					User safeUser = userService.selectUserByUserId("safesecret");
					messageService.insertMessage("还原用户"+userNames+"", "用户管理", null,safeUser.getId(), "", "0","K");
				}
			}
			
		}
//		user.setLogout((long) logout);
//		user=userService.selectByPrimaryKey(user.getId());
//		HttpSession session = request.getSession();
//		String userName=(String) session.getAttribute("userName");
//		String logName="还原用户";
//		String comments=userName+"将"+user.getUserName()+"还原用户 ";
//		if(logout==1){
//			logName="注销用户";
//			comments=userName+"将"+user.getUserName()+"用户注销";
//		}
//		auditLogService.insertLog(logName, "用户管理", comments,request);
		return "0";	
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转修改密码页面
	 * @return
	 *@date 2016-06-24
	 */
	@RequestMapping(value = {"/editPwdPage" })
	public String editPwdPage(){
		HttpSession session = request.getSession();
		String userId=session.getAttribute("userId").toString();
		
		List<SafeManagement> list=safeManagementService.selectInfo();
		SafeManagement safeManagement = list.get(0);
		
		request.setAttribute("userId", userId);
		Long pwdMinLength=(long) 0;
		Long pwdMaxLength=(long) 0;
		if(safeManagement!=null){
			pwdMinLength=safeManagement.getMinimumPwdLength();
			pwdMaxLength=safeManagement.getMaximumPwdLength();
		}
		request.setAttribute("pwdMinLength",pwdMinLength );
		request.setAttribute("pwdMaxLength", pwdMaxLength);

		return "user/editPwdPage";	
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转密码重置页面
	 * @return
	 *@date 2016-06-24
	 */
	@RequestMapping(value ="/userPwdResetList",produces = "application/json; charset=utf-8")
	@ResponseBody
	public PaginationUtil userPwdResetList(String name){
		PaginationUtil paginationUtil = new PaginationUtil();
		paginationUtil.before(request);
		if("请输入姓名...".equals(name))      // 内容信息与显示一致 
			name = null;
		
		List<?> user = userService.pwdResetList(name);
		paginationUtil.after(user);
		return paginationUtil;
	}
	/**
	 *@author 申鹏飞
	 *@title 修改密码
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value="/editPwd",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxMessage editPwd(@ModelAttribute User user){
		AjaxMessage ajaxMessage = new AjaxMessage();
		HttpSession session = request.getSession();
		try {
			String type = request.getParameter("type");
			session.setAttribute("type", type);
			User selectByPrimaryKey = userService.selectByPrimaryKey(getUser_idFormSession("user_id"));
			
			if(!EncryptUtil.md5(user.getPasswordOld()).equals(selectByPrimaryKey.getPassword())){
				ajaxMessage.setCode("0");
				ajaxMessage.setMessage("原密码输入不正确！");
				return ajaxMessage;
			}
			user.setId(selectByPrimaryKey.getId());
			user.setPasswordOld(user.getPasswordOld());
			user.setPassword(EncryptUtil.md5(user.getPassword()));
			user.setUserPwdModifTime(DateUtils.getDate("yyyy-MM-dd HH:mm"));
			userService.updateByPrimaryKey(user);
			ajaxMessage.setCode("1");
			ajaxMessage.setMessage("修改成功");
			userAuditLogService.insertLog("修改密码", "修改密码", getUser_idFormSession("userName")+"修改了密码", request);
		} catch (Exception e) {
			logger.error(e);
			ajaxMessage.setCode("0");
			ajaxMessage.setMessage("系统错误,请联系管理员");
		}
		return ajaxMessage;
	}
	/**
	 *@author 申鹏飞
	 *@title 重置密码
	 * @return
	 *@date 2016-06-30
	 */
	@RequestMapping(value="/PwdReset",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String PwdReset(String userId){
		HttpSession session = request.getSession();
		String userName = (String) session.getAttribute("userName");
		String[] userIds =userId.split(",");
		String userNames = "";
		for(String id:userIds){
			User user = new User();
			String passsword = "";//IdGenerator.random10Str();
			String numCode = getUser_idFormSession("customCode");
			if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
				passsword = "intec@1234";
			}else{
				passsword = IdGenerator.random10Str();
			}
			user.setPassword(EncryptUtil.md5(passsword));
			user.setPasswordOld(passsword);
			user.setUserPwdModifTime(DateUtils.getDate("yyyy-MM-dd HH:mm"));
			user.setInitPwdTime(DateUtils.formatDateTime(new Date()));
			user.setExitTime(DateUtils.getDate("yyyy-MM-dd HH:mm"));
			user.setId(id);
			userService.updateByPrimaryKey(user);
			User u = userService.selectByPrimaryKey(id);
			if("".equals(userNames)){
				userNames = u.getUserName();
			}else{
				userNames += "," + u.getUserName();
			}
		}
		//重置密码的日志
		String  numCode = getUser_idFormSession("customCode");
		String comments = userName + "将" + userNames + "用户的密码重置";
		auditLogService.insertLog("重置密码", "用户列表", comments, request);
		if(numCode != null && numCode.equals(ProjectIdentNew.tianjin712)){
			User safeUser = userService.selectUserByUserId("safesecret");
			messageService.insertMessage("系统管理员重置了用户名为"+userNames+"的密码", "用户管理", null,safeUser.getId(), "", "0","K");
		}
		return "重置成功";
	}
	/**
	 *@author 申鹏飞
	 *@title 排序上下位置
	 * @returnz
	 *@date 2016-06-30
	 */
	@RequestMapping(value = "/updateSort",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String updateSort(@ModelAttribute User user){
		//排序方式
		String type = request.getParameter("type");
		
		if(user != null){
			//List<User> selectAll = userService.selectAll(null);
			User selectUser = new User();
			String user_idFormSession = getUser_idFormSession("userId");
			if("sysadmin".equals(user_idFormSession))
				selectUser.setIsSys("sysadmin");
			
			if("请输入姓名...".equals(user.getUserNameForSerch())){
				selectUser.setUserNameForSerch(null);
			}
			selectUser.setUserStatus(1L);
			selectUser.setProjectSource(Constant.projectName);
			List<User> selectAll = userService.selectByUserInfo(selectUser);			
			
			int flag = 0;
			for(int i=0;i<selectAll.size();i++){
				User user2 = selectAll.get(i);
				if(user.getId().equals(user2.getId())){
					flag = i;
					break;
				}
			}
				
			if("0".equals(type)){
				if(flag == 0)
					return "无法上移";
				flag --;
			}else{
				if(flag == (selectAll.size()-1))
					return "无法下移";
				flag ++ ;
			}
			
			String sort = user.getSort();
			
			User user2 = selectAll.get(flag);
			
			User user3 = new User();
			user3.setId(user.getId());
			user3.setSort(user2.getSort());
			userService.updateSort(user3);
			user3.setId(user2.getId());
			user3.setSort(sort);
			userService.updateSort(user3);
			return "操作成功";    // 修改提示信息为 操作成功
		}

		return Constant.ERROE_MESSAGE;	
	}
	
	/**
	 *@ author 申鹏飞
	 *@ title 获取部门人员
	 *@ return
	 *@ date 2016-06-30
	 */
	@RequestMapping(value = "/selectDepartUser",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String selectDepartUser(@ModelAttribute User user){
		List<User> list = new ArrayList<User>();
		String departId = request.getParameter("departId");
		String set_document_departId = request.getParameter("set_document_departId") == null ? "" : request.getParameter("set_document_departId");
		String source = request.getParameter("source") == null ? "" : request.getParameter("source");
		String userName = request.getParameter("value");
		logger.info("查询条件="+userName);
		//获取项目密级
		String projectClassIficationName = request.getParameter("projectClassIficationName") == null? "" : request.getParameter("projectClassIficationName");
		//获取标识
		String  customer = getUser_idFormSession("customCode");
		if("sysadmin".equals(getUser_idFormSession("userId"))){
			user.setIsSys("sysadmin");
		}
		user.setFlag("1");
		if(!"".equals(set_document_departId)){
			Department department = departmentService.selectByPrimaryKey(set_document_departId);
			if(department != null){
				List<User> users = null;
				if(customer != null && customer.equals(ProjectIdentNew.siyuan17suo)){
					if(userName == null || "搜索您想寻找的...".equals(userName)){
						users = userService.selectDepartUser17suo(department.getParentId());
					}else{
						user.setUserNameForSerch(userName);
						//修改[#3329]BUG,搜索本部门的人只出本部门下的人员
						user.setDepartId(department.getParentId());
						user.setProjectSource(Constant.projectName);
						users = userService.selectByUserInfo17suo(user);
					}
					//根据项目密级过滤用户
					Iterator<User> userIterator = users.iterator();
					while (userIterator.hasNext()){
						User u = userIterator.next();
						//获取一般涉密人员、重要涉密人员、核心涉密人员
						if("内部".equals(projectClassIficationName) || "秘密".equals(projectClassIficationName)){
							if(!("10".equals(u.getSecret()) || "20".equals(u.getSecret()) || "30".equals(u.getSecret())) ){
								userIterator.remove();
							}
						}
						//获取重要涉密人员、核心涉密人员
						if("机密".equals(projectClassIficationName)){
							if(!("20".equals(u.getSecret()) || "30".equals(u.getSecret())) ){
								userIterator.remove();
							}
						}
					}
				}else {
					if(userName == null || "搜索您想寻找的...".equals(userName)){
						users = userService.selectDepartUser(department.getParentId());
					}else{
						user.setUserNameForSerch(userName);
						//修改[#3329]BUG,搜索本部门的人只出本部门下的人员
						user.setDepartId(department.getParentId());
						user.setProjectSource(Constant.projectName);
						users = userService.selectByUserInfo(user);
					}

				}
				return JsonUtils.arrayListToJsonString(users);
			}
		}else{
			if(customer != null && (customer.equals(ProjectIdentNew.siyuan17suo) || customer.equals(ProjectIdentNew.guiyangshiyuan))){
				//17所查询数据返回对象中有人员密级数据
				if(StringUtils.hasText(userName)){
					if(!"搜索您想寻找的...".equals(userName))
						user.setUserNameForSerch(userName);
					List<User> selectByUserInfo = userService.selectByUserInfo17suo(user);
					list.addAll(selectByUserInfo);
				}else{
					if(!"".equals(source)){
						user.setDepartId(departId);
						List<User> users = userService.selectByUserInfo17suo(user);
						list.addAll(users);
					}else{
						HashSet<String> selectByparentId = departmentService.selectByparentId(departId);
						user.setDepartId(departId);
						List<User> us = userService.selectByUserInfo17suo(user);
						list.addAll(us);
						for(String deptId : selectByparentId){
							user.setDepartId(deptId);
							List<User> users = userService.selectByUserInfo17suo(user);
							list.addAll(users);
						}
					}

				}
				//根据项目密级过滤用户
				Iterator<User> userIterator = list.iterator();
				while (userIterator.hasNext()){
					User u = userIterator.next();
					//获取一般涉密人员、重要涉密人员、核心涉密人员
					if("内部".equals(projectClassIficationName) || "秘密".equals(projectClassIficationName)){
						if(!("10".equals(u.getSecret()) || "20".equals(u.getSecret()) || "30".equals(u.getSecret())) ){
							userIterator.remove();
						}
					}
					//获取重要涉密人员、核心涉密人员
					if("机密".equals(projectClassIficationName)){
						if(!("20".equals(u.getSecret()) || "30".equals(u.getSecret())) ){
							userIterator.remove();
						}
					}
				}
			}else {
				if(StringUtils.hasText(userName)){
					if(!"搜索您想寻找的...".equals(userName))
						user.setUserNameForSerch(userName);
					List<User> selectByUserInfo = userService.selectByUserInfo(user);
					list.addAll(selectByUserInfo);
				}else{
					if(!"".equals(source)){
						user.setDepartId(departId);
						List<User> users = userService.selectByUserInfo(user);
						list.addAll(users);
					}else{
						HashSet<String> selectByparentId = departmentService.selectByparentId(departId);
						user.setDepartId(departId);
						List<User> us = userService.selectByUserInfo(user);
						list.addAll(us);
						for(String deptId : selectByparentId){
							user.setDepartId(deptId);
							List<User> users = userService.selectByUserInfo(user);
							list.addAll(users);
						}
					}
				}
			}
		}
		//去除重复数据
	    List listnew = new ArrayList();
	    for (User user1 : list) {
	    	if(!listnew.contains(user1)){
	    		listnew.add(user1);
	    	}
		}
		return JsonUtils.toJson(listnew);	
	}
	
	/**
	 *@author 申鹏飞
	 *@title 获取部门人员
	 * @return
	 *@date 2016-06-30
	 */
	@RequestMapping(value = "/addUserList",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String addUserList(){
		String departId=request.getParameter("departId");
		List<User> user = userService.selectDepartUser(departId);
		return JsonUtils.arrayListToJsonString(user);	
	}
	
	
	/**
	 * 
	 * @Title: showBatchImport
	 * @Description: 上传用户列表
	 * @return
	 * @author 赵亚舟
	 * @return String
	 */
	@RequestMapping(value = "/showBatchImport",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public String showBatchImport(String rand){
		request.setAttribute("rand", rand);
		return "/user/uploadUserExcl";
	}
	
	/**
	 * 
	 * @Title: analysisExcl
	 * @Description: 解析excl,上传用户
	 * @param multipartfile
	 * @return
	 * @author 赵亚舟
	 * @return AjaxMessage
	 */
	@ResponseBody
	@RequestMapping(value="/analysisExcl",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	public AjaxMessage analysisExcl(MultipartFile multipartfile){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			Workbook workbook = WorkbookFactory.create(multipartfile.getInputStream());
			//获取第一个sheet
			Sheet sheet = workbook.getSheetAt(0);
			//检查标题
			userService.checkFirstRowName(ajaxMessage, sheet);
			if("0".equals(ajaxMessage.getCode()))
				return ajaxMessage;
			//验证数据，并插入数据库
			HttpSession session = request.getSession();
			String userName = (String) session.getAttribute("userName");	
			String message = userService.insertUser(sheet,userName,request);
			ajaxMessage.setCode("1");
			ajaxMessage.setMessage(message);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			ajaxMessage.setCode("0");
		}
		
		return ajaxMessage;
	}

	/**
	 * 
	 * @Title: downloadExcl
	 * @Description: 下载文件
	 * @author 赵亚舟
	 * @return void
	 */
	@RequestMapping(value="/downloadExcl",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public void downloadExcl(HttpServletResponse response){
		
		try {
			String fileName = "批量导入用户模板";
			String customer = getUser_idFormSession("customCode");
			if(ProjectIdentNew.huayin.equals(customer)){
				fileName = "批量导入用户模板华阴专用";
			}
			String path = request.getSession().getServletContext().getRealPath("")+File.separator+"resources"+File.separator+"model"+File.separator+fileName+".xlsx";
			File file = new File(path);
			
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            
            response.setCharacterEncoding("UTF-8");
            //response.setContentType("application/vnd.ms-excel");
            response.setContentType("application/octet-stream");
            // IE  
			if (request.getHeader("user-agent").toLowerCase().contains("msie")||request.getHeader("user-agent").toLowerCase().contains("like gecko") ) {
				response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GB2312"), "ISO8859-1" ) +".xlsx"+ "\"");
			}else{
				response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1" ) +".xlsx"+ "\"");
			}
		       
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
			
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 *@author 贺雷雷
	 *@title 发送代办消息
	 * @return
	 *@date 2019-05-20
	 */
	@RequestMapping(value="/sendMessage",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public void sendMessage(String userId){
		HttpSession session = request.getSession();
		String[] userIds = userId.split(",");
		User safeUser = userService.selectUserByUserId("safesecret");
		for(String id:userIds){
			User u = userService.selectByPrimaryKey(id);
			String userName = u.getUserName();
		    String comments = (String) session.getAttribute("userName") + "重置了用户" + userName +"的密码信息";
	        auditLogService.insertLog("重置密码", "重置密码", comments, request);
			messageService.insertMessage("系统管理员重置了用户名为"+userName+"的密码", "重置密码", null,safeUser.getId(), id, "1","K");
		 
		}
	}
	/**
	 *@author 贺雷雷
	 *@title 重置密码
	 * @return
	 *@date 2019-05-20
	 */
	@RequestMapping(value="/PwdResetMessage",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public void PwdResetMessage(String userIds,User user){
		HttpSession session = request.getSession();
		String[] userIdStr = userIds.split(",");
		for(String userId: userIdStr){
			String passsword="intec@1234";//IdGenerator.random10Str();
			user.setPassword(EncryptUtil.md5(passsword));
			user.setPasswordOld(passsword);
			user.setUserPwdModifTime(DateUtils.getDate("yyyy-MM-dd HH:mm"));
			user.setInitPwdTime(DateUtils.formatDateTime(new Date()));
			user.setExitTime(DateUtils.getDate("yyyy-MM-dd HH:mm"));
			user.setId(userId);
			userService.updateByPrimaryKey(user);
			User u = userService.selectByPrimaryKey(userId);
			String comments = (String) session.getAttribute("userName") + "同意系统管理员重置用户名为"+u.getUserName()+"密码的请求";
		    auditLogService.insertLog("重置密码", "重置密码", comments, request);
		}
	}
	
	/**
	 *@author 贺雷雷
	 *@title 已登录用户页面
	 * @return
	 *@date 2019-08-5
	 */
	@RequestMapping(value="/loginUserList",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public String loginUserList(){
		String  numCode = numberBuilderService.getCustomerId();
		request.setAttribute("numCode", numCode);
		return "user/loginUserList";
	}
	/**
	 *@author 贺雷雷
	 *@title 查询已登录用户
	 * @return
	 *@date 2019-08-5
	 */
	@RequestMapping(value = "/selectLoginList",produces = "application/json; charset=utf-8")
	@ResponseBody
	public PaginationUtil selectLoginList(String userNameForSerch){
		PaginationUtil paginationUtil = new PaginationUtil();
		paginationUtil.before(request);
	    Collection<Session> sessions = sessionDAO.getActiveSessions();//获取当前已登录的用户session列表
	    List<String> list = new ArrayList<String>();
	    Map<String,String> maploginIp = new HashMap<String,String>();
	    Map<String,String> maploginTime = new HashMap<String,String>();
	      for(Session session:sessions){
	    	  Date date =  session.getStartTimestamp();
              String loginIp = SessionCounter.sessionIpMap.get(session.getId());
              SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              String loginTime = formatter.format(date);
	          String userId = (String) session.getAttribute("user_id");
	          if(userId != null){
	        	  maploginIp.put(userId, loginIp);
	              maploginTime.put(userId, loginTime);
	              list.add(userId);
	          }
	       }
		List<User> userList = userService.selectAllLogin(list,userNameForSerch);
		for(User user:userList){
			user.setiP(maploginIp.get(user.getId()));
			user.setLoginTime(maploginTime.get(user.getId()));
		}
		paginationUtil.after(userList);
		return paginationUtil;
	}
	/**
	 *@author 贺雷雷
	 *@title 注销用户
	 *@return	
	 *@date 2019-09-18
	 */
	@RequestMapping(value = "/sessionDestroy",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String sessionDestroy(String id){
		/*Collection<Session> sessions = sessionDAO.getActiveSessions();//获取当前已登录的用户session列表
		String loginIp = request.getRemoteAddr();
		for(Session session:sessions){
	          String userId = (String) session.getAttribute("user_id");
	  	      String secctionId = request.getSession().getId();
	          if(!id.equals(userId)){
	               continue;
	          }
               if(SessionCounter.activeSessions>0){
                   if(SessionCounter.list.size() > 0){
                       for(int i = 0;i < SessionCounter.list.size(); i ++){
                           if(loginIp.equals(SessionCounter.list.get(i))){
                             	SessionCounter.list.remove(i);  
                           }
                       }
                   }
                   SessionCounter.sessionIpMap.remove(secctionId);
                   SessionCounter.activeSessions--;//在用户销毁的时候,从队列中踢出这个IP
                   session.stop();
               }
		}*/
		//获取shiro的sessionManager
	    DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
	    DefaultWebSessionManager sessionManager = (DefaultWebSessionManager)securityManager.getSessionManager();
	    // 3.获取所有已登录用户的session列表
        Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();
        String loginIp = request.getRemoteAddr();
		for(Session session:sessions){
	          String userId = (String) session.getAttribute("user_id");
	  	      String secctionId = request.getSession().getId();
	          if(!id.equals(userId)){
	               continue;
	          }
               if(SessionCounter.activeSessions>0){
                   if(SessionCounter.list.size() > 0){
                       for(int i = 0;i < SessionCounter.list.size(); i ++){
                           if(loginIp.equals(SessionCounter.list.get(i))){
                             	SessionCounter.list.remove(i);  
                           }
                       }
                   }
                   SessionCounter.sessionIpMap.remove(secctionId);
                   SessionCounter.activeSessions--;//在用户销毁的时候,从队列中踢出这个IP
                   sessionManager.getSessionDAO().delete(session);
               }
		}
		return "yes";
	}
	/**
	 * @Title: showExcelImportIdcast
	 * @Description: 显示当前下载页面
	 * @param rand
	 * @return
	 * @author 雒乐
	 * @return String
	 */
	@RequestMapping(value = "/showExcelImportIdcast",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public String showExcelImportIdcast(String rand){
		request.setAttribute("rand", rand);
		return "/user/uploadExclInIdcard";
	}
	/**
	 * @Title: downloadExcelIn
	 * @Description: 下载需要上传的用户身份证号码
	 * @param response
	 * @param fileName
	 * @author 雒乐
	 * @return void
	 */
	@RequestMapping(value="/downloadExcelIn",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public void downloadExcelIn(HttpServletResponse response){
		
		try {
			String fileName="批量导入用户身份证号码模板";
			String path = request.getSession().getServletContext().getRealPath("")+File.separator+"resources"+File.separator+"model"+File.separator+fileName+".xlsx";
			File file = new File(path);
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            // IE  
			if (request.getHeader("user-agent").toLowerCase().contains("msie")||request.getHeader("user-agent").toLowerCase().contains("like gecko") ) {
				response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("GB2312"), "ISO8859-1" ) +".xlsx"+ "\"");
			}else{
				response.setHeader("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("utf-8"), "ISO8859-1" ) +".xlsx"+ "\"");
			}
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
	}
	/**
	 * @Title: importExcelIdcard
	 * @Description: 导入用户身份证号码
	 * @param multipartfile
	 * @return
	 * @author 雒乐
	 * @return AjaxMessage
	 */
	@ResponseBody
	@RequestMapping(value="/importExcelIdcard",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	public AjaxMessage importExcelIdcard(MultipartFile multipartfile){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			Workbook workbook = WorkbookFactory.create(multipartfile.getInputStream());
			Sheet sheet = workbook.getSheetAt(0);
			userService.checkFirstRowNameIdcard(ajaxMessage, sheet);
			if("0".equals(ajaxMessage.getCode()))
				return ajaxMessage;
			//楠岃瘉鏁版嵁锛屽苟鎻掑叆鏁版嵁搴�
			HttpSession session = request.getSession();
			String userName = (String) session.getAttribute("userName");	
			String message = userService.updateUserIdcard(sheet,userName,request);
			ajaxMessage.setCode("1");
			ajaxMessage.setMessage(message);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			ajaxMessage.setCode("0");
		}
		return ajaxMessage;
	}
	
	
	/**
	 * 
	 * @Title: checkUserCountExceptAdmin
	 * @Description: 查询除了三员和sysadmin 外是否有其他没有部门的 用户
	 * @param multipartfile
	 * @return
	 * @author 车飞挺
	 * @date: 2020年4月23日 下午6:01:06
	 * @return AjaxMessage
	 */
	@ResponseBody
	@RequestMapping(value="/selectNoDeptUserCountExceptAdmin",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public AjaxMessage selectNoDeptUserCountExceptAdmin(){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			
			List<User> userList = userService.selectNoDeptUserCountExceptAdmin();
			JSONObject rsData = new JSONObject();
			if(userList!= null && userList.size()>0){
				rsData.put("userList", JSON.toJSONString(userList));
				rsData.put("count", userList.size());
				ajaxMessage.setCode("1");
				ajaxMessage.setData(rsData.toJSONString());
			}else{
				rsData.put("count", 0);
				ajaxMessage.setCode("1");
				ajaxMessage.setData(rsData.toJSONString());
			}
			
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
			ajaxMessage.setCode("0");
		}
		return ajaxMessage;
	}
	
	
	
	
}
